﻿/*
 *
 * Date: 2014/08/20
 * Author: Neil Zeng
 *
 */

/*! http://mths.be/placeholder v2.0.7 by @mathias */

;(function(window, document, $) {

	var isInputSupported = 'placeholder' in document.createElement('input');
	var isTextareaSupported = 'placeholder' in document.createElement('textarea');
	var prototype = $.fn;
	var valHooks = $.valHooks;
	var propHooks = $.propHooks;
	var hooks;
	var placeholder;

	if (isInputSupported && isTextareaSupported) {

		placeholder = prototype.placeholder = function() {
			return this;
		};

		placeholder.input = placeholder.textarea = true;

	} else {

		placeholder = prototype.placeholder = function() {
			var $this = this;
			$this
				.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
				.not('.placeholder')
				.bind({
					'focus.placeholder': clearPlaceholder,
					'blur.placeholder': setPlaceholder
				})
				.data('placeholder-enabled', true)
				.trigger('blur.placeholder');
			return $this;
		};

		placeholder.input = isInputSupported;
		placeholder.textarea = isTextareaSupported;

		hooks = {
			'get': function(element) {
				var $element = $(element);

				var $passwordInput = $element.data('placeholder-password');
				if ($passwordInput) {
					return $passwordInput[0].value;
				}

				return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
			},
			'set': function(element, value) {
				var $element = $(element);

				var $passwordInput = $element.data('placeholder-password');
				if ($passwordInput) {
					return $passwordInput[0].value = value;
				}

				if (!$element.data('placeholder-enabled')) {
					return element.value = value;
				}
				if (value == '') {
					element.value = value;
					// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
					if (element != document.activeElement) {
						// We can't use `triggerHandler` here because of dummy text/password inputs :(
						setPlaceholder.call(element);
					}
				} else if ($element.hasClass('placeholder')) {
					clearPlaceholder.call(element, true, value) || (element.value = value);
				} else {
					element.value = value;
				}
				// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
				return $element;
			}
		};

		if (!isInputSupported) {
			valHooks.input = hooks;
			propHooks.value = hooks;
		}
		if (!isTextareaSupported) {
			valHooks.textarea = hooks;
			propHooks.value = hooks;
		}

		$(function() {
			// Look for forms
			$(document).delegate('form', 'submit.placeholder', function() {
				// Clear the placeholder values so they don't get submitted
				var $inputs = $('.placeholder', this).each(clearPlaceholder);
				setTimeout(function() {
					$inputs.each(setPlaceholder);
				}, 10);
			});
		});

		// Clear placeholder values upon page reload
		$(window).bind('beforeunload.placeholder', function() {
			$('.placeholder').each(function() {
				this.value = '';
			});
		});

	}

	function args(elem) {
		// Return an object of element attributes
		var newAttrs = {};
		var rinlinejQuery = /^jQuery\d+$/;
		$.each(elem.attributes, function(i, attr) {
			if (attr.specified && !rinlinejQuery.test(attr.name)) {
				newAttrs[attr.name] = attr.value;
			}
		});
		return newAttrs;
	}

	function clearPlaceholder(event, value) {
		var input = this;
		var $input = $(input);
		if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
			if ($input.data('placeholder-password')) {
				$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
				// If `clearPlaceholder` was called from `$.valHooks.input.set`
				if (event === true) {
					return $input[0].value = value;
				}
				$input.focus();
			} else {
				input.value = '';
				$input.removeClass('placeholder');
				input == document.activeElement && input.select();
			}
		}
	}

	function setPlaceholder() {
		var $replacement;
		var input = this;
		var $input = $(input);
		var id = this.id;
		if (input.value == '') {
			if (input.type == 'password') {
				if (!$input.data('placeholder-textinput')) {
					try {
						$replacement = $input.clone().attr({ 'type': 'text' });
					} catch(e) {
						$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
					}
					$replacement
						.removeAttr('name')
						.data({
							'placeholder-password': $input,
							'placeholder-id': id
						})
						.bind('focus.placeholder', clearPlaceholder);
					$input
						.data({
							'placeholder-textinput': $replacement,
							'placeholder-id': id
						})
						.before($replacement);
				}
				$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
				// Note: `$input[0] != input` now!
			}
			$input.addClass('placeholder');
			$input[0].value = $input.attr('placeholder');
		} else {
			$input.removeClass('placeholder');
		}
	}
	
	
}(this, document, jQuery));


$(function(){
	// Initialize placeholder
	//$('input, textarea').placeholder("");
});


var regexRadio = /^(?:radio)$/i, regexCheckbox = /^(?:checkbox)$/i, regexSelectMultiple = /^select-multiple$/i, regexSelect = /^(?:select)/i, regexTextarea = /^(?:textarea)/i, regexInput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i;
jQuery.fn.extend({	
	serializeForm2Object : function() {
		var Form2Object = new Object();
		this.map(function() {
					return this.elements ? $.makeArray(this.elements) : this;
				}).filter(function() {
			return this.name && !this.disabled 
					&& (regexRadio.test(this.type)
							|| regexCheckbox.test(this.type)
							|| regexSelect.test(this.nodeName)
							|| regexTextarea.test(this.nodeName) || regexInput
							.test(this.type));
		}).map(function(i, elem) {
					var eleName = elem.name;
					var val = $(this).val();
					val = val == null ? "" : val;
					if ($.type(val) === "string") {
						val = $.trim(val);
					}
					if (regexCheckbox.test(this.type)) {
						var inputchecked = $(this).is(':checked');
						if (inputchecked === true || inputchecked == "checked") {
							if (Form2Object[eleName] != null) {
								if ($.isArray(Form2Object[eleName])) {
									Form2Object[eleName].push(val);
								} else {
									var temp = Form2Object[eleName];
									Form2Object[eleName] = [];
									Form2Object[eleName].push(temp);
									Form2Object[eleName].push(val);
								}
							} else {
								Form2Object[eleName] = val;
							}
							
						}
					} else if (regexRadio.test(this.type)) {
						var inputchecked = $(this).is(':checked');
						if (inputchecked === true || inputchecked == "checked") {
							Form2Object[eleName] = val;
						}
					} else {
						if (Form2Object[eleName] != null) {
							if ($.isArray(Form2Object[eleName])) {
								Form2Object[eleName].push(val);
							} else {
								var temp = Form2Object[eleName];
								Form2Object[eleName] = [];
								Form2Object[eleName].push(temp);
								Form2Object[eleName].push(val);
							}
						} else {
							Form2Object[eleName] = val;
						}

					}
				});
		return Form2Object;
	}
	
	
});

jQuery.extend({
	/**
	 * Simple JavaScript Templating John Resig - http://ejohn.org/ - MIT
	 * Licensed
	 * 
	 * @param {String}
	 *            str
	 * @param {Object}
	 *            data 
	 * @return {String}
	 */
	pushDataToTemplate : function(str, data) {
		// Figure out if we're getting a template, or if we need to
		// load the template - and be sure to cache the result.
		var fn = !/\W/.test(str) ? cache[str] = cache[str]
				|| tmpl(document.getElementById(str).innerHTML) :

				// Generate a reusable function that will serve as a template
				// generator (and which will be cached).
				new Function("obj",
						"var p=[],print=function(){p.push.apply(p,arguments);};"
								+

								// Introduce the data as local variables using
								// with(){}
								"with(obj){p.push('" +

								// Convert the template into pure JavaScript
								str.replace(/[\r\t\n]/g, " ").split("<%")
										.join("\t").replace(/((^|%>)[^\t]*)'/g,
												"$1\r").replace(/\t=(.*?)%>/g,
												"',$1,'").split("\t")
										.join("');").split("%>")
										.join("p.push('").split("\r")
										.join("\\'") + "');}return p.join('');");

		// Provide some basic currying to the user
		return data ? fn(data) : fn;
	},
	myShowModalDialog : function (url,obj,style){
		//如果是chrome window.open()
		if(navigator.userAgent.indexOf("Chrome") >0 ){
			 window.open(url,obj,style); 
		}else{
			 window.showModalDialog(url,obj,style);
		}
	},
	myWindowLocationHref : function (url){
		//如果是IE
		if(navigator.userAgent.indexOf("MSIE")>0) {
			 window.location.href(url);
		}else{
			 window.location.href = url;
		}
	},
	end : "end"
});

Date.prototype.Format = function(formatStr){   
    var str = formatStr;   
    var Week = ['日','一','二','三','四','五','六'];  
  
    str=str.replace(/yyyy|YYYY/,this.getFullYear());   
    str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));   
  
    str=str.replace(/MM/,this.getMonth()>9?(this.getMonth()+1).toString():'0' + (this.getMonth()+1));   
    str=str.replace(/M/g,(this.getMonth()+1));   
  
    str=str.replace(/w|W/g,Week[this.getDay()]);   
  
    str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());   
    str=str.replace(/d|D/g,this.getDate());   
  
    str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());   
    str=str.replace(/h|H/g,this.getHours());   
    str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());   
    str=str.replace(/m/g,this.getMinutes());   
  
    str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());   
    str=str.replace(/s|S/g,this.getSeconds());   
  
    return str;   
};

function showSuccessMsg(msg,callback){
	bootstrapQ.bs.msg({
	     msg  : msg,
	     type : 'success',
	     time : 1000,
	    callback:callback
	 });
} 

function showErrMsg(msg,callback){
	bootstrapQ.bs.msg({
	     msg  : msg,
	     type : 'danger',
	     time : 2000,
	    callback:callback
	 });
} 



function logout_common(){
	showErrMsg("您长时间未操作，为确保安全，请重新登录。",function(){
		top.location.href = "/loan/springmvc/login_halo";
	})
} 



function DataSetObject(url, successcallback, config) {
	if (!(this instanceof DataSetObject)) {
		return new DataSetObject(url, successcallback, config);
	}
	this.dataResult = null;
	
	this.params ={
			dataType : "json",
			type : "POST",
			async : false,
			traditional : false,  //true时,阻止深度序列化 p: ["123", "456", "789"]    =>    p=123&p=456&p=456
			contentType : "application/x-www-form-urlencoded; charset=UTF-8",
			errorshowCallback: commonerrorshow
	};
	
	if (arguments.length > 1) {
		if (jQuery.type(arguments[1]) === "function") {
			this.successCallback = arguments[1];
		}
		this.params.async = false;
	}
	
	this.url ="" + arguments[0];
	
	if (arguments.length > 2) {
		 this.params = $.extend( this.params, config);
	}
	
	
}

function commonerrorshow(id,message) {
	 var errormsgid ="errormsg_"+id;
	 
	 
	 var errorelement = '<ul id="' + errormsgid +  '" class="parsley-error-list"><li class="required" style="display: list-item;">' + message + '</li></ul>';
	
	if($("#" + id).length > 0 ){
		 $("#" + id).after(errorelement);
	}else{
		 $("[name='" + id + "'").after(errorelement);
	}
	
	$("#" + errormsgid).bind("click", function(){
		$(this).fadeOut(800);
		$("#" + errormsgid).remove();
	});
	
	
	setTimeout( function(){
		$("#" + errormsgid).click();
	}, 5 * 1000 );
	
	
};


DataSetObject.prototype.setSuccessCallback = function(callback) {
	if (jQuery.type(callback) === "function") {
		this.successCallback = callback;
	}
	return this;
};

DataSetObject.prototype.setErrorCallback = function(callback) {
	if (jQuery.type(callback) === "function") {
		this.errorCallback = callback;
	}
	return this;
};

DataSetObject.prototype.call = function(objdate) {
	$("[id^='errormsg']").remove();
	jQuery.ajax({
				url : this.url,
				type : this.params.type,
				async : this.params.async,
				dataType : this.params.dataType,
				contentType: this.params.contentType,
				traditional: this.params.traditional,
				context : this,
				data : objdate,
				success : function(dataResult, textStatus) {
					
					if(dataResult != null){
						//有错误时，调用写错误函数。
						if(dataResult.errorMap != null){
							$("[id^='errormsg']").remove();
							var errorshow = this.params.errorshowCallback;
							var eachIndex=0;
							$.each(dataResult.errorMap, function(i, n){			
								    var id = ""+i;
						            var message = ""+n;
						            errorshow(id,message);
						            if(eachIndex == 0){
						            	$("#" + id).focus();
						            }
						            eachIndex =eachIndex+1;
								});
							if (jQuery.type(this.errorCallback) === "function") {
								this.errorCallback(dataResult, textStatus);
							}
							return;
						}
					}

						
					if (jQuery.type(this.successCallback) === "function") {
						this.successCallback(dataResult, textStatus);
					}
					this.dataResult = dataResult;
					
				}
			});
	return this.dataResult;
};

//modeltype  del,
function ModalObject(modaltype,config){
	
	
	if (!(this instanceof ModalObject)) {
		return new ModalObject(modaltype,config);
	}
	this.modaltype = modaltype;
	this.modalcontent = "";
	this.params ={
			modalid: "commonmodal",
			title: "",
			content: "",
			okhidden: true,
			okfunction: "",
			jsobj: ""   //js object 为了兼容iframe，先找到iframe，在弹出
   };
   this.params = $.extend( this.params, config);
   var obj = this;
   
   obj.iniModal();
}

ModalObject.prototype = {
		iniModal: function(){
			
			$(top.document).find("#"+this.params.modalid).remove();
			if(this.modaltype == 'del'){
				this.modalcontent = '  <div class="modal-header">'
				                    + ' <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>'
				                    + '   <h4 class="modal-title" id="commonLabel">' + this.params.title + '</h4>'
				                    + ' </div>'
				                    + '  <div class="modal-body">'
				                    + '      <p class="div-content">' + this.params.content + '</p>'
				                    + '  </div>'
				                    + '  <div class="modal-footer rcs-text-center">'
				                    + '     <button type="button" class="btn btn-primary" id="modal_ok_button" data-dismiss="modal">' +"确定"+'</button>'
				                    + '    <button type="button" class="btn btn-default" data-dismiss="modal">' + "取消" +'</button>'
				                    + '  </div>';
			}
			
			var modalHTML =  '<div class="modal fade rcs-delete-modal" id="' +  this.params.modalid + '" tabindex="-1" role="dialog" aria-labelledby="commonLabel" aria-hidden="true"  data-backdrop="static">'
				+ '  <div class="modal-dialog">'
				+ '    <div class="modal-content">'
				+   this.modalcontent                
				+ '    </div>'
				+ '  </div>'
				+ '</div>'

			$(top.document).find("body").append(modalHTML);
			
			var obj = this;
				
			$(top.document).find("#modal_ok_button").click(function(){
				if(typeof(obj.params.okfunction) === "function"){
					obj.params.okfunction(obj.params.data);
				}else{
					obj.hide();
				}
			});
			
			$(top.document).find('#'+this.params.modalid).on('hidden.bs.modal', function () {
				$(top.document).find('#'+obj.params.modalid).remove();				
			});
			
		},
		show:function(css){
			if(css != null){
				$(top.document).find("#"+this.params.modalid).modal('show').css(css);
			}else{
				$(top.document).find("#"+this.params.modalid).modal('show');
			}
			
			
		},
		hide:function(){
			$(top.document).find("#"+this.params.modalid).modal('hide');
		},
};

//加法函数  
function accAdd(arg1, arg2) {  
    var r1, r2, m;  
    try {  
        r1 = arg1.toString().split(".")[1].length;  
    }catch (e) {  
        r1 = 0;  
    }  
    try {  
        r2 = arg2.toString().split(".")[1].length;  
    }catch (e) {  
        r2 = 0;  
    }  
    m = Math.pow(10, Math.max(r1, r2));  
    return (arg1 * m + arg2 * m) / m;  
}   
//给Number类型增加一个add方法，，使用时直接用 .add 即可完成计算。   
Number.prototype.add = function (arg) {  
    return accAdd(arg, this);  
};  
  
//减法函数  
function Subtr(arg1, arg2) {  
    var r1, r2, m, n;  
    try {  
        r1 = arg1.toString().split(".")[1].length;  
    }catch (e) {  
        r1 = 0;  
    }  
    try {  
        r2 = arg2.toString().split(".")[1].length;  
    }catch (e) {  
        r2 = 0;  
    }  
    m = Math.pow(10, Math.max(r1, r2));  
     //last modify by deeka  
     //动态控制精度长度  
    n = (r1 >= r2) ? r1 : r2;  
    return ((arg1 * m - arg2 * m) / m).toFixed(n);  
}  
  
//给Number类型增加一个add方法，，使用时直接用 .sub 即可完成计算。   
Number.prototype.sub = function (arg) {  
    return Subtr(this, arg);  
};  
  
//乘法函数  
function accMul(arg1, arg2) {  
    var m = 0, s1 = arg1, s2 = arg2; 
	 try {  
        s1 = arg1.toString();  
    }catch (e) {  
	   s1 = 0;
    } 
	
	try {  
        s2 = arg2.toString();  
    }catch (e) {  
	   s2 = 0;
    } 
	
    try {  
        m += s1.split(".")[1].length;  
    }catch (e) {  
	   
    }  
	
    try {  
        m += s2.split(".")[1].length;  
    }catch (e) {  
	  
    }  
	var result = 0;
	try {  
       result = Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
    }catch (e) {  
	  result = 0;
    } 
	
    return result;  
}   
//给Number类型增加一个mul方法，使用时直接用 .mul 即可完成计算。   
Number.prototype.mul = function (arg) {  
    return accMul(arg, this);  
};   

function validateMoney(){

	$("body").delegate("input","change",function(e){
        var checktype = $(this).attr("check");
		
		if(checktype == "money"){
			//校验金额
			var el =  /^[0-9]+.?[0-9]*$/;
			var checkVal = $(this).val();
			var idName = $(this).attr("id");
			if (!checkVal.match(el)&&checkVal!="") {
				$(this).val('');
				$(this).focus();
				alert("只能输入整数或者小数！");
			}
		}else if(checktype == "zhengShu"){
			//校验整数
			var el = /^\d+$/;
			var checkVal = $(this).val();
			var idName = $(this).attr("id");
			if (!checkVal.match(el)&&checkVal!="") {
				$(this).val('');
				$(this).focus();	
				alert("只能输入整数！");				
			}
			
		}
		
	});
}
  
//除法函数  
function accDiv(arg1, arg2) {  
    var t1 = 0, t2 = 0, r1, r2;  
    try {  
        t1 = arg1.toString().split(".")[1].length;  
    }  
    catch (e) {  
	    
    }  
    try {  
	
		if(arg2 == null || arg2 == 0 || arg2 =="0"){
			return 0;
		}
        t2 = arg2.toString().split(".")[1].length;  
    }  
    catch (e) {  
	  
    }  
    with (Math) {  
        r1 = Number(arg1.toString().replace(".", ""));  
        r2 = Number(arg2.toString().replace(".", ""));  
        var num = (r1 / r2) * pow(10, t2 - t1); 
        return num.toFixed(4)	;	
    }  
}   
//给Number类型增加一个div方法，，使用时直接用 .div 即可完成计算。   
Number.prototype.div = function (arg) {  
    return accDiv(this, arg);  
};   

function replaceListName(){
	$("tbody").each(function(index,element){
		var listname = $(this).attr("listname");
		if(listname != null){
			$(this).find("tr").each(function(index,element){
				var listnumber = index;
				$(this).find("[name^='" + listname + "']").each(function(index,element){
					var name = $(this).attr("name");					
					name = listname + "["+listnumber+"]" + name.substring(name.indexOf("."));			
					$(this).attr("name",name);
				})
			});
			
		}
	})
}

function iniselect(){
	$("select").each(function(){
		var value = $(this).attr("oldvalue");
		if(value !=null && value != ""){
			$(this).val(value);	
		}
	});
}

function iniselect2(){
	$(".select2").select2({
	    width: '100%'
	});
}

$(".table-responsive tbody :checkbox").click(function(event){
    event.stopPropagation();
    var $tmp=$(this).closest("tbody").find(":checkbox").not(":disabled,:hidden");
    var checked = $tmp.length==$tmp.filter(':checked').not(":disabled,:hidden").length;
    $(this).closest("table").find("thead :checkbox").prop('checked',checked);
    DGCheckboxCtrl();
})  

//表头checkbox
$(".table-responsive thead :checkbox").click(function(event){
    event.stopPropagation();
    var itemChk = $(this).closest("table").find("tbody :checkbox").not(":disabled,:hidden");
    itemChk.prop("checked", this.checked);
    DGCheckboxCtrl();
})

function DGCheckboxCtrl(){
    $(".table-responsive tbody :checkbox").parents("tr").removeClass("on");
    $(".table-responsive tbody :checked").parents("tr").addClass("on");
}

function openwindow(url){
	window.open(url);  
}
